package cn.sdhuijin.healthexam.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.util.Properties;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;
import cn.sdhuijin.healthexam.R;
import cn.sdhuijin.healthexam.util.Util;

public class UpdateService extends Service {

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		setUpdateFileDefault();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onStart(Intent intent, int startId) {
		update();
	}

	public void update() {
		new Thread() {
			public void run() {
				Properties properties = new Properties();
				try {
					File file = new File(
							Environment.getExternalStorageDirectory()
									+ "/health/update.txt");
					Log.i(this.getClass().getSimpleName(),
							"路径" + file.getAbsolutePath());
					properties.load(new FileReader(file.getAbsolutePath()));
					String updateUrl = properties.getProperty("检测网址");
					if (Util.allIsNotEmpty(updateUrl)) {
						Log.e("检测网址", "已设置：" + updateUrl);
						if (Util.isNetAvailable(UpdateService.this
								.getBaseContext())) {
							Log.e("网络", "已连接");
							String ver = Util.sendHttpGet(updateUrl
									+ "version.txt", "v=" + Util.version);
							if (Util.allIsNotEmpty(ver)
									&& !ver.trim().equals(Util.version)) {
								Log.i("比较结果", "有新版本");
								addNotificaction(ver);
							}
						} else {
							Log.e("网络", "尚未连接");
						}
					} else {
						Log.e("检测网址", "尚未设置");
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.start();
	}

	/**
	 * 添加一个notification
	 */
	private void addNotificaction(String version) {
		NotificationManager manager = (NotificationManager) this
				.getSystemService(Context.NOTIFICATION_SERVICE);

		Uri uri = Uri.parse("http://huijin.qiniudn.com/healthexam/client-"
				+ version + ".apk");
		Intent intent = new Intent(Intent.ACTION_VIEW, uri);
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
				intent, PendingIntent.FLAG_ONE_SHOT);
		// 创建一个Notification
		Notification.Builder notification = new Notification.Builder(
				this.getBaseContext()).setContentTitle("医疗终端 ")
				.setContentText("有新的版本，请点击此处进行更新")
				.setSmallIcon(R.drawable.ic_launcher).setAutoCancel(true)
				.setContentIntent(pendingIntent);

		manager.notify(200, notification.build());

	}

	/**
	 * 若系统更新参数所保存的文件不存在，则新建文件，写入默认参数
	 */
	public void setUpdateFileDefault() {
		Properties properties = null;
		File file = null;
		File dirFile = null;
		try {
			properties = new Properties();
			dirFile = new File(Environment.getExternalStorageDirectory()
					+ "/health/");
			if (!dirFile.exists()) {
				dirFile.mkdirs();
			}
			file = new File(Environment.getExternalStorageDirectory()
					+ "/health/update.txt");
			if (!file.exists()) {
				file.createNewFile();
				saveUpdateSetting(file, properties);
			} else {
				properties.load(new FileInputStream(file));
				String updateUrl = properties.getProperty("检测网址");
				if (!Util.allIsNotEmpty(updateUrl)) {
					saveUpdateSetting(file, properties);
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 保存默认设置
	 * 
	 * @param file
	 * @param properties
	 * @throws Exception
	 */
	private void saveUpdateSetting(File file, Properties properties)
			throws Exception {
		FileInputStream fileInputStream = null;
		FileOutputStream fileOutputStream = null;
		fileInputStream = new FileInputStream(file);
		properties.load(fileInputStream);
		// 检测网址
		properties.setProperty("检测网址", "http://huijin.qiniudn.com/healthexam/");
		// 检测周期
		properties.setProperty("检测周期", "1");
		fileOutputStream = new FileOutputStream(
				Environment.getExternalStorageDirectory()
						+ "/health/update.txt");
		// 保存
		properties.store(fileOutputStream, "系统更新设置参数信息");
	}

}
